//
//  MyOrderViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/10.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//
//  我的订单
import UIKit
import MJRefresh
import Networking
import Alamofire
import PKHUD
import SwiftyJSON


//0:待付款；1：待发货；2：待收货；3：已完成；4：已取消；5：申请退换；6：同意退货；7：拒绝退货
enum OrderDetailType: Int {
    case waitPay = 0
    case waitOut
    case out
    case done
    case cancel
    case req
    case agree
    case none
    
}
enum MineOrderContentType1: NSInteger {
    case comment = 0
    case zan
}
class MyOrderViewController: BaseViewController, ImageFactory, WCLWaterFallLayoutDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, AddCornerUIRectCorner, BottomShadow, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {
    private let itemTopBottomMargin: CGFloat =  10
    private let itemOffset: CGFloat = 10
    let cellHeight: CGFloat = 85
    @IBOutlet weak var mainSearchView: UIView!
    @IBOutlet weak var mainCollectionView: UICollectionView!
    @IBOutlet weak var cornerSelectionView: CornerSelectionView!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var screenButton: UIButton!
    @IBOutlet weak var mainTableView: UITableView!
    
    var model: myOrderModel?
    private var commodityModels1: [GoodsSCModel] = []
    private var orderModels: [myOrderModel] = []
    private var itemSize: CGSize {
        let LRMargin: CGFloat = 20
        let width = (ScreenWidth - LRMargin * 2 - itemOffset) / 2
        let height: CGFloat = 260
        return CGSize(width: width, height: height)
        
    }
    
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    // 顶部刷新
    let header1 = MJRefreshNormalHeader()
    // 底部刷新
    let footer1 = MJRefreshAutoNormalFooter()
    
    var page:Int = 0
    var totalPage:Int = 0
    var keyword :String = ""
    var mineContentType: MineOrderContentType1 = .comment

    private let consultationHeight: CGFloat = 125
    private let headerViewHeight: CGFloat = 200
    private let cellMaxHeight: Int = 359
    private let cellMinHeight: Int = 280
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
    }
    
    func setUI() {
        titleLabel(text: "我的订单", nil)
        screenButton.layoutIfNeeded()
        mainTableView.register(UINib(nibName: "\(MyOrderTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        
        setSearchBar()
        screenButton.imageEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)
        
//        mainTableView.layoutIfNeeded()
//        mainTableView.tableFooterView = setBottomView()
        
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        mainTableView.mj_header = header
        mainTableView.mj_footer = footer
        mainTableView.bounces = true
        
        mainCollectionView.register(UINib(nibName: "\(MyOrderSCCell.self)", bundle: nil), forCellWithReuseIdentifier: "myOrderSCCell")
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = itemSize
        layout.minimumLineSpacing = itemTopBottomMargin
        layout.minimumLineSpacing = itemOffset
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsetsMake(itemTopBottomMargin, itemOffset, itemTopBottomMargin, itemOffset)
        mainCollectionView.collectionViewLayout = layout
    
        mainCollectionView.clipsToBounds = true
        
        let headerAction1:Selector = #selector(headerRefresh1)
        header1.setRefreshingTarget(self, refreshingAction: headerAction1)
        
        let footerAction1:Selector = #selector(footerRefresh1)
        footer1.setRefreshingTarget(self, refreshingAction: footerAction1)
        mainCollectionView.mj_header = header1
        mainCollectionView.mj_footer = footer1
        
        self.headerRefresh()
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh()
    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        switch self.mineContentType {
        case .comment:
            self.fetchBannerList(parameters: ["page":page,"pageSize":10,"keyword":keyword,"status":""])
        case .zan:
            self.fetchProductList(parameters: ["page":page,"pageSize":10,"objType":3])
        }
    }
    
    // 顶部刷新
    @objc func headerRefresh1(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh1()
    }
    // 底部刷新
    @objc func footerRefresh1(){
        print("上拉刷新")
        page += 1
     
        self.fetchProductList(parameters: ["page":page,"pageSize":10,"objType":3])
    }
    
    override func setNavigation() {
    }
    
    override func returnVC() {
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    func setSearchBar() {
        cornerSelectionView.show(titles: ["订单", "收藏"]) {[unowned self] (index) in
            var corner: UIRectCorner!
            switch index {
            case 0:
                self.mainSearchView.isHidden = false
                self.mainTableView.isHidden = false
                self.mainCollectionView.isHidden = true
                self.fetchBannerList(parameters: ["page":1,"pageSize":10,"keyword":self.keyword,"status":""])
                corner = [.topRight,.bottomLeft, .bottomRight]
            case 2:
                corner = [.topLeft, .bottomLeft, .bottomRight]
            default:
                self.mainSearchView.isHidden = true
                self.mainTableView.isHidden = true
                self.mainCollectionView.isHidden = false
                self.fetchProductList(parameters: ["page":1,"pageSize":10,"objType":3])
                corner = .allCorners
            }
            self.mineContentType = MineOrderContentType1(rawValue: index)!
        }
        
        searchBar.delegate = self
        searchBar.barStyle = .blackTranslucent
        let searchImage = createImage(color: UIColor(hex: 0xBFBFBF), height: 28)
        searchBar.backgroundImage = searchImage
    
        searchBar.backgroundColor = UIColor.clear
        searchBar.setSearchFieldBackgroundImage(searchImage, for: .normal)
        searchBar.layer.cornerRadius = CORNERRADIUS
        searchBar.layer.masksToBounds = true
        let searchField = searchBar.value(forKey: "searchField") as? UITextField
        if let textField = searchField {
            textField.layer.cornerRadius = CORNERRADIUS
            textField.layer.masksToBounds = true
            textField.backgroundColor = UIColor.white
            textField.attributedPlaceholder = NSAttributedString(string: "订单编号/收件人名称/收件人电话", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 9)])
            textField.textColor = UIColor.white
            textField.font = UIFont.systemFont(ofSize: 10)
            let imageView = UIImageView(image: UIImage(named: "icon_search"))
            imageView.sizeToFit()
//            textField.delegate = self
            textField.leftView = imageView
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return orderModels.count
    }
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let order = orderModels[section]
        if let count = order.purchaseGoodsInfos?.count{
            return count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 52
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 35))
        let lable: UILabel = UILabel(frame: .zero)
        lable.font = UIFont.systemFont(ofSize: 10)
        lable.textColor = UIColor.black
        let model = orderModels[section]
        lable.text = model.orderNumber
        lable.left = 15
        lable.sizeToFit()
        lable.centerY = view.centerY;
        view.addSubview(lable)
        
        let button: UILabel = UILabel(frame: .zero)
        button.font = UIFont.systemFont(ofSize: 10)
        button.textColor = UIColor.red
        if let type = OrderDetailType(rawValue: Int(model.status!)!) {
           typeUI(type: type, typeLabel: button, rightButton: UIButton())
        }
        button.sizeToFit()
        button.right = view.right - 30
        button.centerY = view.centerY
        view.addSubview(button)
        view.backgroundColor = UIColor.white
//        addCornerWithView(aView: view, aCorners: [.bottomLeft, .bottomRight, .topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        
        return view
    }
    

    //0:待付款；1：待发货；2：待收货；3：已完成；4：已取消；5：申请退换；6：同意退货；7：拒绝退货
    private func typeUI(type: OrderDetailType, typeLabel: UILabel, rightButton: UIButton) {
        var leftButtonIsHidden = true
        var rightButtonColor = UIColor(hex: 0x8F8F8F)
        var typeTitle = ""
        var typeTitleColor = ONColor.currencyRedColor
//        0:待付款；1：待发货；2：待收货；3：已完成；4：已取消；5：申请退换；6：同意退货；7：拒绝退货
        switch type {
        case .waitPay:
            typeTitle = "待付款"
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("立即付款", for: .normal)
        case .waitOut:
            typeTitle = "待发货"
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("催单", for: .normal)
        case .out:
            typeTitle = "待收货"
            rightButtonColor = ONColor.currencyRedColor
            leftButtonIsHidden = false
            rightButton.setTitle("确认收货", for: .normal)
        case .done:
            typeTitle = "已完成"
            typeTitleColor = ONColor.normalTextColor
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("再次购买", for: .normal)
        case .cancel:
            typeTitle = "已取消"
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("立即付款", for: .normal)
        case .req:
            typeTitle = "申请退换"
            leftButtonIsHidden = false
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("申请售后", for: .normal)
        case .agree:
            typeTitle = "同意退货"
            typeTitleColor = ONColor.normalTextColor
            rightButton.setTitle("再次购买", for: .normal)
        case .none:
            typeTitle = "拒绝退货"
            typeTitleColor = ONColor.normalTextColor
            rightButton.setTitle("再次购买", for: .normal)
        }
        
        typeLabel.textColor = typeTitleColor
        typeLabel.text = typeTitle
//        leftButton.isHidden = leftButtonIsHidden
        rightButton.layer.borderColor = rightButtonColor.cgColor
        rightButton.setTitleColor(rightButtonColor, for: .normal)
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 52))
        let lable: UILabel = UILabel(frame: .zero)
        lable.font = UIFont.systemFont(ofSize: 10)
        lable.textColor = UIColor.black
        let model = orderModels[section]
        let per = model.purchaseGoodsInfos!
        var total: Float = 0
        for item in per {
            let json = JSON(item.totalPrice)
            total += json.floatValue
        }
        lable.text = "共" + model.totalCount! + "件 ￥" + "\(total)"
        lable.left = 15
        lable.sizeToFit()
        lable.centerY = view.centerY - 10;
        view.addSubview(lable)
        
        let button: UILabel = UILabel(frame: .zero)
        button.font = UIFont.systemFont(ofSize: 8)
        button.textColor = UIColor.gray
        button.text = "运费：￥" + model.carriage!
        button.sizeToFit()
        button.left = lable.right + 10
        button.centerY = view.centerY - 10
        view.addSubview(button)
        
        let button1: UIButton = UIButton(frame: .zero)
        button1.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        button1.titleLabel?.textColor = UIColor.red
        
        if model.status == "0" {
            typeUI(type: .waitPay, typeLabel: UILabel(), rightButton: button1)
        }else{
          if let type = OrderDetailType(rawValue: Int(model.status!)!) {
               typeUI(type: type, typeLabel: UILabel(), rightButton: button1)
            }
        }
        button1.width = 80
        button1.height = 30
        button1.layer.masksToBounds = true
        button1.layer.cornerRadius = 15
        button1.layer.borderWidth = 1
        button1.right = view.right - 30
        button1.centerY = view.centerY - 10
        button1.tag = section
        button1.addTarget(self, action: #selector(pay(btn:)), for: .touchUpInside)
        view.addSubview(button1)
        
        if model.status == "4" {
            button1.isHidden = false
            button1.setTitle("再次购买", for: .normal)
            button1.setTitleColor(UIColor.gray, for: .normal)
            button1.layer.borderColor = UIColor.gray.cgColor
        }
        
        let button2: UIButton = UIButton(frame: .zero)
        button2.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        button2.titleLabel?.textColor = UIColor.red
        
        
        if let type = OrderDetailType(rawValue: section) {
            typeUI(type: type, typeLabel: UILabel(), rightButton: button2)
        }
        button2.width = 80
        button2.height = 30
        button2.layer.masksToBounds = true
        button2.layer.cornerRadius = 15
        button2.layer.borderWidth = 1
        button2.right = button1.left - 3
        button2.centerY = view.centerY - 10
        button2.tag = section
        button2.addTarget(self, action: #selector(delete(btn:)), for: .touchUpInside)
        view.addSubview(button2)
        if model.status == "4" {
            button2.isHidden = false
            button2.setTitle("删除订单", for: .normal)
            button2.setTitleColor(UIColor.gray, for: .normal)
            button2.layer.borderColor = UIColor.gray.cgColor
        }else{
            button2.isHidden = true
        }
        
        view.backgroundColor = UIColor.white
//        setShadow(view: view, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
//        addCornerWithView(aView: view, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        let image:UIImageView = UIImageView(frame: CGRect(x: 0, y: 10, width: ScreenWidth - 20, height: 17))
        image.image = UIImage(named: "bg_cut_shadow")
        view.addSubview(image)
        image.bottom = view.bottom
//        addCornerWithView(aView: view, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: 2, height: 2))
//        setShadow(view: view, opacity: bottomShadowOpacity, size: CGSize(width: 0, height: 2), color: UIColor.black, cornerradius: 2)
//        view.layer.shadowOpacity = 0.9
//        view.layer.shadowRadius = 6
//        view.shadow(UIColor.black, opacity: 0.9, radius: 6, offset: CGSize(width: 1, height: 1))
//        view.rounded(4)
//
//        view.layer.zPosition = 100
        return view
    }
    @objc func pay(btn: UIButton){
        guard let currentTitle = btn.currentTitle else { return  assert(false, "按钮Title没有设置")}
        self.someButtonTap(cell: btn.tag, title: currentTitle)
        
    }
    
    @objc func delete(btn: UIButton){
        let index = btn.tag
        let mode = orderModels[index]
        deleteOrder(paramaters: ["id": mode.id!])
    }
    
    func deleteOrder(paramaters: [String: String]) -> Void {
        let requesturl = appendUrl(suffix: deleteOrderUrl)
        Alamofire.request(requesturl, method: .get,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        
                                        self.showToast(msg:json["message"].string!)
                                        self.page = 1
                                        self.fetchBannerList(parameters: ["page":self.page,"pageSize":10,"keyword":self.keyword,"status":""])
                                        
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? MyOrderTableViewCell
        cell?.backgroundColor = UIColor.white
        if let type = OrderDetailType(rawValue: indexPath.row) {
            cell?.setData(type: type)
        }
//        addCornerWithView(aView: (cell?.contentView)!, aCorners: [.bottomLeft, .bottomRight, .topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        let model = orderModels[indexPath.section].purchaseGoodsInfos![indexPath.row]
        cell?.bindData(data: model)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = self.orderModels[indexPath.section]
        
        if model.status != nil {
            if let sta: Int = Int(model.status!), sta > 5 {
                return
            }
        }
        
        let myDetailOrderVC = MyDetailOrderViewController(nibName: "\(MyDetailOrderViewController.self)", bundle: nil)
       var title = ""
        switch Int(model.status!)! {
//            0:待付款；1：待发货；2：待收货；3：已完成；4：已取消；5：申请退换；6：同意退货；7：拒绝退货
        case 0:
            title = "待付款"
            myDetailOrderVC.orderDetailType = .waitPay
        case 1:
            title = "待发货"
            myDetailOrderVC.orderDetailType = .waitOut
        case 2:
            title = "待收货"
            myDetailOrderVC.orderDetailType = .out
        case 3:
            title = "已完成"
            myDetailOrderVC.orderDetailType = .done
        case 4:
            title = "已取消"
            myDetailOrderVC.orderDetailType = .cancel
        case 5:
            title = "申请退换"
            myDetailOrderVC.orderDetailType = .req
        case 6:
            title = "同意退货"
            myDetailOrderVC.orderDetailType = .agree
        case 7:
            title = "拒绝退货"
            myDetailOrderVC.orderDetailType = .none
        default:
            myDetailOrderVC.orderDetailType = .waitPay
        }
        myDetailOrderVC.titleLabel(text: title, nil)
        myDetailOrderVC.cancelblock = {
            self.page = 1
            self.fetchBannerList(parameters: ["page":self.page,"pageSize":10,"keyword":self.keyword,"status":""])
        }
        myDetailOrderVC.deleteblock = {
            self.page = 1
            self.fetchBannerList(parameters: ["page":self.page,"pageSize":10,"keyword":self.keyword,"status":""])
        }
        myDetailOrderVC.model = model
        self.navigationController?.pushViewController(myDetailOrderVC, animated: true)
    }
    
    func setHeaderView() -> UIView {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.white
        headerView.frame = CGRect(x: 0, y: 0, width: mainTableView.width, height: 20)
        return headerView
    }
    
    func setBottomView() -> UIView {
        let bottomView = UIView()
        bottomView.backgroundColor = UIColor.white
        bottomView.frame = CGRect(x: 0, y: 0, width: mainTableView.width, height: 10)
        addCornerWithView(aView: bottomView, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        return bottomView
    }
    
    // MARK: - collectionViewDataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      
        return commodityModels1.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let shoppingDetailVC = ShoppingDetailViewController(nibName: "\(ShoppingDetailViewController.self)", bundle: nil)
        let temp = commodityModels1[indexPath.row]
        var model = GoodsModel()
        model.id = temp.id
        model.coverPath = temp.image
        model.type = temp.redirectType
        model.shareUrl = temp.share
        model.collected = temp.collected
        shoppingDetailVC.commodityModel = model
        self.navigationController?.pushViewController(shoppingDetailVC, animated: true)
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myOrderSCCell", for: indexPath) as? MyOrderSCCell
        cell?.setData(model: commodityModels1[indexPath.row])
        return cell!
    }
//    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        <#code#>
//    }
//    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//        let cell1:MyOrderSCCell  = cell as! MyOrderSCCell
//
//    }
    
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForItemAt indexPath: IndexPath) -> CGFloat {
        //        let model: GoodsModel = commodityModels[indexPath.row
        //        ]
        //        let height = ShoppingListCollectionViewCell.caculateHeight(model: model)
        
        return 250
    }
    
    func columnOfWaterFall(_ collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForHeaderAt indexPath: IndexPath) -> CGFloat {
        return 0
    }
    func waterFall(_ collectionView: UICollectionView, layout waterFallLayout: WCLWaterFallLayout, heightForFooterAt indexPath: IndexPath) -> CGFloat {
        return 0
    }
    
    /// 获取商品数据
    func fetchProductList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(myShoucangUrl)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        if self.page == 1{
                                            self.commodityModels1.removeAll()
                                            self.mainCollectionView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainCollectionView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            let model = GoodsSCModel(fromDic: dic)
                                            self.commodityModels1.append(model)
                                        }
                                        if self.totalPage == self.commodityModels1.count{
                                            self.mainCollectionView.mj_footer.isHidden = true
                                        }
                                        else{
                                            self.mainCollectionView.mj_footer.isHidden = false
                                        }
                                        
                                        self.mainCollectionView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainCollectionView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainCollectionView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.mainCollectionView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainCollectionView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
    }
    
    /// 获取banner数据
    func fetchBannerList(parameters: [String: Any]) -> Void {
        let requesturl = "\(BaseURL)\(myOrderListUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        if self.page == 1{
                                            self.orderModels.removeAll()
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = myOrderModel(fromDic: dic)
                                            model.initLabels(arr: (dic["purchaseGoodsInfos"]?.array!)!)
                                       
                                            self.orderModels.append(model)
                                        }
                                      
                                        if self.totalPage == self.orderModels.count{
                                            self.mainTableView.mj_footer = nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                      self.mainTableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                if self.page == 1{
                                    self.mainTableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTableView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    // MARK: - MyOrderTableViewCellDelegate
    func someButtonTap(cell: Int, title: String) {
        let mode = self.orderModels[cell]
        switch title {
          
        case "再次购买":
            let buyNowVC = BuyNowViewController(nibName: "\(BuyNowViewController.self)", bundle: nil)
            buyNowVC.type = 3
            buyNowVC.orderNumber = mode.orderNumber
            self.navigationController?.pushViewController(buyNowVC, animated: true)
//            // TODO: 测试
//            let logisticsDetailsVC = LogisticsDetailsViewController(nibName: "\(LogisticsDetailsViewController.self)", bundle: nil)
//            self.navigationController?.pushViewController(logisticsDetailsVC, animated: true)
            
        case "进行评价":
            let evaluateVC = EvaluateViewController(nibName: "\(EvaluateViewController.self)", bundle: nil)
            self.navigationController?.pushViewController(evaluateVC, animated: true)
        case "立即付款":
//            let pendingPaymentVC = PendingPaymentViewController()
//            self.navigationController?.pushViewController(pendingPaymentVC, animated: true)
                let payVC = PayViewController(nibName: "PayViewController", bundle: nil)
                payVC.titleLabel(text: "选择支付方式", nil)
                payVC.orderId = self.orderModels[cell].orderNumber
                self.navigationController?.pushViewController(payVC, animated: true)
            break
        case "催单":
            self.fetchreminder(parameters: ["id":(mode.id)!])
            break
        case "确认收货":
            self.fetchConfirmReceived(parameters: ["id":(mode.id)!])
            break
        case "查看进度":
            break
        default:
            break
        }
    }
    
    /// 催单
    func fetchreminder(parameters: [String: String]) -> Void {
        let requesturl = "\(BaseURL)\(reminder)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        CustomShowAlertView().show(title: "小蜜已收到你的请求，正在为您抓紧处理！还请稍安勿躁~", tapClosure: {})
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 确认收货
    func fetchConfirmReceived(parameters: [String: String]) -> Void {
        let requesturl = "\(BaseURL)\(confirmReceived)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                        self.fetchBannerList(parameters: ["page":1,"pageSize":10,"keyword":self.keyword,"status":""])
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
   
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        self.keyword = searchBar.text!
        self.fetchBannerList(parameters: ["page":1,"pageSize":10,"keyword":self.keyword,"status":""])
    }
    func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            searchBar.resignFirstResponder()
            return false
        }
        return true
    }
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
    }
    
    @IBAction func statusQuery(_ sender: Any) {
        let imageSize = UIImage(named: "right_copy_page")
        guard let trueImageSize = imageSize else {return}
        var data: [SearchRecommendModel] = []
        let datas = ["全部", "待付款", "待发货", "待收货", "已完成", "已取消", "申请售后"]
        for subject in datas {
            var se = SearchRecommendModel()
            se.title = subject
            data.append(se)
        }
        if data.count > 0{
            RelevantRecommendationsView().showData(datas: data, rightMargin: trueImageSize.size.width * trueImageSize.scale - 50){(index) in
                if index == 0 {
                  self.fetchBannerList(parameters: ["page":1,"pageSize":10,"keyword":self.keyword,"status":""])
                }else{
                    let idxStr = "\(index! - 1)"
                    self.fetchBannerList(parameters: ["page":1,"pageSize":10,"keyword":self.keyword,"status":idxStr])
                }
            }
        }
        else{
            self.showToast(msg:"没有数据")
        }
    }
    
}
